package cn.edu.xmu.tangzk.scala.byexs

import scala.annotation.tailrec

object Ex05_2_1 {

    val EmptySum = 0

    /**
     * 求f(a)+...+f(b)的和
     */
    def linearSum(f: Int => Int)(a: Int, b: Int): Int = {
        if (a > b) EmptySum
        else { f(a) + linearSum(f)(a + 1, b) }
    }

    def sum(f: Int => Int)(a: Int, b: Int): Int = {
        @tailrec def iter(a: Int, result: Int): Int = {
            if (a > b) result
            else iter(a + 1, result + f(a))
        }
        iter(a, EmptySum)
    }

    def main(args: Array[String]) {
        val result0 = sum(x => x)(2, 4)
        val result1 = linearSum(x => x)(2, 4)
        println(result0, result1)
        assert(result0 == result1)
    }
}